package org.itstack.demo.design;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * @Author: fanYuLe
 * @CreateTime: 2023-12-29  10:28
 * @Description:
 */
public class HttpClient {

    public static String doGet(String httpUrl){
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null; //返回结果字符串
        try {
            //创建远程URL连接对象
            URL url = new URL(httpUrl);
            //通过远程url连接对象打开一个连接，强转成httpUrlConnection类
            connection = (HttpURLConnection) url.openConnection();
            //设置连接方式：get
            connection.setRequestMethod("GET");
            //设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            //设置读取远程返回数据的超时时间：60000毫秒
            connection.setReadTimeout(60000);
            //发送请求
            connection.connect();
            //通过connection连接，获取输入流
            if(connection.getResponseCode() == 200){
                is = connection.getInputStream();
                //封装输入流is,并指定字符集
                br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
                // 存放数据
                StringBuilder sbf = new StringBuilder();
                String temp =null;
                while ((temp = br.readLine())!=null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }  catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            if(null!=br){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(null!=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            assert connection !=null;
            connection.disconnect(); //关闭远程连接
        }
        return result;
    }
}
